<!--待复习单词列表-->
<template>
    <!--新增单词-->
    <el-row align="middle" :gutter="5" style="margin-top: 5px;">
        <el-col :span="12"><el-tag class="ml-2" type="success" size="large" style="display: flex;">待复习列表</el-tag></el-col>
        <el-col :span="8">
                <el-input 
                    v-model="newWordForm.word" 
                    :prefix-icon="Search" 
                    placeholder="记新单词" />
            </el-col>
        <el-col :span="4"><el-button type="primary" :loading="loadingB" @click="addWord()">确认</el-button></el-col>
    </el-row>
    <el-divider class="itemb itemt"></el-divider>

    <!--表格-->
    <audio style="display: none"  ref="radioRef"  controls></audio>
    <el-table 
        :data="tableData" 
        v-loading="loading"
        :row-class-name="tableRowClassName"
        style="width: 100%;" 
        empty-text="无数据，点击上面记忆新单词"
        max-height="800">
        <!-- <template #append>
            <el-button>加载更多...</el-button>
        </template> -->

        <el-table-column prop="words.wordShow" label="发音" min-width="80" align="right" />
        <el-table-column label="" width="50">
            <template #default="scope">
                <div @click="playAudio(scope.row.words.voiceUrl)">
                    <el-badge :hidden="!scope.row.forgot" value="忘记">
                    </el-badge>
                    <el-icon :size="25"><VideoPlay /></el-icon>
                </div>
            </template>
        </el-table-column>

        <el-table-column prop="words.definition" label="释义" min-width="100" />

        <el-table-column label="你的记忆" width="120">
            <template  #default="scope">
                <input type="hidden" name="progressId" :value="scope.row.id">
                <el-input 
                    class="itemb" 
                    placeholder="输入单词" 
                    v-model="scope.row.reviewWord"
                    readonly
                    @click="openHandwriting(scope.row)"/>
                <el-progress :percentage="scope.row.totalReviewTimes ==0 ? 0 : (scope.row.reviewTimes*1.0/scope.row.totalReviewTimes)*100" 
                    color="#409eff" 
                    :show-text="false"/>
            </template>
        </el-table-column>
        <el-table-column :label="total+''" width="85" >
            <template #default="scope">
                <el-button @click="comfimReview(scope.row, scope.$index)">确认</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!--对话框-->
    <el-dialog v-model="dialogVisible" title="" class="dialogwidth">
        <el-row justify="space-between">
            <el-col :span="8">
                <p class="timep">
                    <el-tag
                        class="ml-2"
                        :type="reviewResult.success ? 'success' : 'danger'"
                        effect="dark"
                    >记忆{{ reviewResult.success ? '成功' : '失败' }}</el-tag>
                </p>
                <p class="timep" v-if="!reviewResult.success"><el-tag class="ml-2 " type="danger">错误输入：{{ reviewResult.input }}</el-tag></p>
                <p class="timep"><el-tag class="ml-2" type="warning">下次记忆时间：{{ reviewResult.nextReviewTime }}</el-tag></p>
            </el-col>
            <el-col :span="6">
                <el-progress type="circle" :percentage="reviewResult.progress.totalReviewTimes ==0 ? 0 : ((reviewResult.progress.reviewTimes*1.0/reviewResult.progress.totalReviewTimes)*100).toFixed(0)" width="80"/>
            </el-col>
        </el-row>

        <el-divider style="margin: 5px;"/>

        <el-row align="middle">
            <div class="container" @click="playAudio(reviewResult.words.voiceUrl)">
                <el-icon :size="25"><VideoPlay /></el-icon>
                <el-tag class="ml-2 tagfontsize" type="success">{{ reviewResult.words.wordShow }}</el-tag>
            </div>
        </el-row>
        <el-row>
            <p v-text="reviewResult.words.definition"></p>
        </el-row>
        <el-row>
            <h2>例句：</h2>
        </el-row>
        <el-row>
            <div v-html="reviewResult.words.exampleSentence"></div>
        </el-row>
    </el-dialog>

    <!-- 替换原来的手写画板对话框 -->
    <el-dialog v-model="keyboardVisible" title="输入单词" width="90%" custom-class="keyboard-dialog">
      <div class="keyboard-container">
        <!-- 显示输入结果区域 -->
        <div class="input-display">
          <el-input 
            v-model="inputValue" 
            placeholder="请输入单词"
            readonly
            size="large"
            style="max-width: 200px; margin: 0 auto; text-align: center;"
            :input-style="{ textAlign: 'center' }"
          />
        </div>
        
        <!-- 键盘区域 -->
        <div class="keyboard-layout">
          <!-- 第一行 -->
          <div class="keyboard-row">
            <el-button v-for="key in 'qwertyuiop'.split('')" 
              :key="key"
              @click="appendKey(key)">
              {{ key }}
            </el-button>
          </div>
          <!-- 第二行 -->
          <div class="keyboard-row">
            <el-button v-for="key in 'asdfghjkl'.split('')" 
              :key="key"
              @click="appendKey(key)">
              {{ key }}
            </el-button>
          </div>
          <!-- 第三行 -->
          <div class="keyboard-row">
            <el-button v-for="key in 'zxcvbnm'.split('')" 
              :key="key"
              @click="appendKey(key)">
              {{ key }}
            </el-button>
            <el-button 
              @click="deleteKey"
              type="danger">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="keyboardVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmInput">确认</el-button>
        </div>
      </template>
    </el-dialog>

</template>

<script setup>
    import {ref, onMounted, nextTick, watch} from 'vue'
    import {reviewList, reviewAdd, wordAdd} from '../apis/review'
    import { Search, Delete } from '@element-plus/icons-vue'

    const total = ref(0)
    const tableData = ref([]);
    const loading = ref(false);
    const loadingB = ref(false);
    const reviewResult = ref({
        success: false,
        words: {
            wordShow: 'news[nju:z,nu:z]',
            voiceUrl: 'http://dictmp3.kekenet.com/mp3/45/b5a3de018630d08e99a83991dffdb2f3.mp3',
            definition: 'n. 母亲；大娘；女修道院院长 vt. 生下；养育；像母亲般关怀或照管 adj. 母亲的；出生地的',
            exampleSentence: '<p>fd</p><p>2323</p>'
        },
        nextReviewTime: '6月13日'
    });
    const dialogVisible = ref(false);
    const keyboardVisible = ref(false)
    const currentRow = ref(null)
    const inputValue = ref('')
    
    function loadData() {
        tableData.value = [];
        loading.value = true;
        reviewList({}).then((res) => {
            // console.log(res);
            
            if(res.data.reviewList && res.data.reviewList.length > 0) {
                for(let i = 0; i < res.data.reviewList.length; i++) {
                    tableData.value.push(res.data.reviewList[i]);
                }
            }
            if(res.data.forgotList && res.data.forgotList.length > 0) {
                for(let i = 0; i < res.data.forgotList.length; i++) {
                    let item = res.data.forgotList[i];
                    item['forgot'] = 1;
                    tableData.value.push(item);
                }
            }
            // tableData.value.push(res.data.forgotList[0]);
            // console.log(tableData)
            total.value = res.data.reviewList.length + res.data.forgotList.length;

        }).finally(() => {
            loading.value = false;
        });
    }

    onMounted(() => {
        loadData();
    });

    const tableRowClassName = ({
        row,
        rowIndex,
    }) => {
        // console.log(rowIndex)
        if (row.forgot) {
            return 'warning-row'
        }
        return ''
    }

    // const tableData = ref([
    // {
    //     progressId: 1,
    //     wordShow: '[\'mʌðə]',
    //     voiceUrl: 'http://wefaljl,.fadlfa./com',
    //     definition: 'n. 母亲；大娘；女修道院院长 vt. 生下；养育；像母亲般关怀或照管 adj. 母亲的；出生地的',
    //     voiceUrl: 'http://dictmp3.kekenet.com/mp3/45/b5a3de018630d08e99a83991dffdb2f3.mp3',
    //     reviewWord: '',
    // },
    // {
    //     progressId: 2,
    //     wordShow: '[\'mʌðə]',
    //     voiceUrl: 'http://wefaljl,.fadlfa./com',
    //     definition: 'n. 母亲；大娘；女修道院院长 vt. 生下；养育；像母亲般关怀或照管 adj. 母亲的；出生地的',
    //     voiceUrl: 'http://dictmp3.kekenet.com/mp3/45/b5a3de018630d08e99a83991dffdb2f3.mp3',
    //     reviewWord: null,
    // },
    // ]);


    

    let radioRef = ref({});
    function playAudio(radioUrl) {
        let audio = radioRef.value;
        audio.src = radioUrl;

        if (audio.paused) {
            audio.play();
        } else {
            audio.pause();
        }
    }

    const reviewForm = {};

    function comfimReview(row, index) {
        // console.log(row)
        if(!row.reviewWord) {
            return;
        }

        reviewForm['progressId'] = row.id;
        reviewForm['reviewWord'] = row.reviewWord;

        reviewAdd(reviewForm).then((res) => {
            // console.log(res);
            reviewResult.value = res.data;
            reviewResult.value['input'] = row.reviewWord;
            dialogVisible.value = true;
            
            tableData.value.splice(index, 1);// 删除该行数据
            total.value -= 1;
        });
    }


    const newWordForm = ref({
        word: '',
        confirm: 0,
    });

    function addWord(confirm = 0) {
        // console.log(confirm)
        newWordForm.value.confirm = confirm;

        if(newWordForm.value.word) {
            loadingB.value = true;

            wordAdd(newWordForm.value).then((res) => {
                // console.log(res);
                
                if(res.code === 'c2001') {//二次确认是否重新记忆存在的单词
                    ElMessageBox.confirm(
                        '你的记忆库已存在 '+ newWordForm.value.word +' ，确认要重新记忆吗？',
                        '温馨提示',
                        {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                        }
                    ).then(() => {
                        addWord(1);// 确认后新增
                    }).catch(() => {
                        // ElMessage({
                        //     type: 'info',
                        //     message: 'Delete canceled',
                        // })
                    })
                }
                else if(res.code === '100') {
                    ElMessage({
                        type: 'success',
                        message: '添加单词成功',
                    })

                    newWordForm.value.word = '';
                    loadData();
                }
                else {
                    ElMessage({
                        type: 'error',
                        message: res.desc,
                    })
                }
                
            }).finally(() => {
                loadingB.value = false;
            });
        }
    }

    function openKeyboard(row) {
        currentRow.value = row
        keyboardVisible.value = true
        inputValue.value = ''
    }

    function appendKey(key) {
        inputValue.value += key
    }

    function deleteKey() {
        inputValue.value = inputValue.value.slice(0, -1)
    }

    function confirmInput() {
        if (currentRow.value) {
            currentRow.value.reviewWord = inputValue.value
        }
        keyboardVisible.value = false
        inputValue.value = ''
    }

    function openHandwriting(row) {
        openKeyboard(row)
    }

</script>

<style>
    .itemb {
        margin-bottom: 2px;
    }
    .itemt {
        margin-top: 5px;
    }
    .el-table .warning-row {
        --el-table-tr-bg-color: var(--el-color-warning-light-9);
    }
    .textright {
        text-align: right;
    }
    .wtips {
        display: flex; 
        align-items: center;
        margin-left: 5px;
    }
    .inputcolor {
        color: #de1414
    }
    .tagfontsize {
        font-size: 1em;
    }
    
    @media screen and (min-width: 320px) {
        .dialogwidth {
            width: 85%;
        }
    }

  @media screen and (min-width: 600px) {
        .dialogwidth {
            width: 50%;
        }
    }
    .keyboard-container {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .input-display {
        padding: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .keyboard-layout {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .keyboard-row {
        display: flex;
        justify-content: center;
        gap: 5px;
    }

    .keyboard-row .el-button {
        width: 45px;
        height: 45px;
        padding: 0;
        text-transform: uppercase;
        font-size: 18px;
    }

    @media screen and (max-width: 768px) {
        .keyboard-row .el-button {
            width: 38px;
            height: 38px;
            font-size: 16px;
        }
    }

    .keyboard-dialog {
        margin-top: 20vh;
    }
</style>